package com.zan.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zan.vo.ResStatus;
import com.zan.vo.ResultVo;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }
        String token = request.getHeader("token");
//        System.out.println(token);
        if (token == null) {
            ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_NOT.code, "请先登录", null);
            // 提示请先登录
            doResponse(response, resultVo);
        } else {
            //根据token从redis中获取⽤户信息
            String s = stringRedisTemplate.boundValueOps(token).get();
            if (s == null) {
                //如果用户信息为空，表示用户未登录或者距离上⼀次访问超过30分钟
                ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_NOT.code, "请先登录", null);
                // 提示请先登录
                doResponse(response, resultVo);
            } else {
                stringRedisTemplate.expire(token, 1, TimeUnit.MINUTES);
                return true;
            }

            /*try {
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("Zan666"); //解析token的SigningKey必须和生成的token时设置的密码一致
                //如果token正确（密码正确+有效期内）则正常执行，否则抛出异常
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;
            } catch (ExpiredJwtException e) {
                ResultVo resultVo = new ResultVo(ResStatus.LOGIN_DAIL_OVERDUE.code, "登录过期，请重新登录！", null);
                doResponse(response, resultVo);
            } catch (UnsupportedJwtException e) {
                ResultVo resultVo = new ResultVo(ResStatus.NO.code, "Token不合法，请自重", null);
                doResponse(response, resultVo);
            } catch (Exception e) {
                ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_NOT.code, "请先登录", null);
                doResponse(response, resultVo);
            }*/
        }
        return false;
    }

    private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVo);
        writer.print(s);
        writer.flush();
        writer.close();
    }
}
